package com.supercell.dao.impl;

import com.supercell.dao.DepartmentDAO;
import com.supercell.dao.PersonDAO;
import com.supercell.entity.Department;
import com.supercell.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.Serializable;

/**
 * Created by WUJO2 on 7/15/2016.
 */
@Repository
public class PersonDAOImpl extends GenericDAOImpl<Person> implements PersonDAO {
    @Autowired
    private DepartmentDAO departmentDAO;

    @Override
    protected Class classOfT() {
        return Person.class;
    }

    @Override
    public void update(Person person) {
        Person oldRecord = get(person.getId());
        if (person.getName() != null) {
            oldRecord.setName(person.getName());
        }
        if (person.getTelephone() != null) {
            oldRecord.setTelephone(person.getTelephone());
        }
        if (person.getBirthday() != null) {
            oldRecord.setBirthday(person.getBirthday());
        }
        if (person.getSalary() != null) {
            oldRecord.setSalary(person.getSalary());
        }
        getSession().update(oldRecord);
    }

    @Override
    public Serializable save(Person person) {
        Department department = departmentDAO.get(person.getDepartmentID());
        if (department == null) {
            return null;
        } else {
            person.setDepartment(departmentDAO.get(person.getDepartmentID()));
        }
        return super.save(person);
    }
}
